﻿using System.Threading.Tasks;
using System;
using Microsoft.AspNetCore.Mvc;
using XBLMS.Configuration;
using XBLMS.Core.Utils;
using XBLMS.Enums;
using XBLMS.Models;
using XBLMS.Utils;
using System.Net;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;

namespace XBLMS.Web.Controllers.Home
{
    public partial class LoginController
    {
        [HttpGet, Route(RouteSso)]
        public async Task<ActionResult<QwSubmitResult>> QwSubmit()
        {
            string State = StringUtils.GetRandomString(18);
            string Url = await HttpClientUtils.AuthUri();
            string RedirectUri = await HttpClientUtils.RedirectUri();
            return new QwSubmitResult
            {
                RedirectUrl = Url + "?response_type=code&client_id=lms&scope=openid profile email&redirect_uri=" + RedirectUri + "&state=" + State
            };
        }

        [HttpPost, Route(RouteSso)]
        public async Task<ActionResult<SubmitResult>> QwSubmitLogin([FromBody] QwSubmitRequest request)
        {
            User user;
            var config = await _configRepository.GetAsync();
            var ipAddress = PageUtils.GetIpAddress(Request);

            _logger.LogInformation($"登录code={request.Code}, state = {request.State}");
            string account = await HttpClientUtils.PostUserName(request.Code, request.State);

            string userName;
            string errorMessage;
            (user, userName, errorMessage) = await _userRepository.ValidateAsync(account);

            if (user == null)
            {
                user = await _userRepository.GetByUserNameAsync(userName);
                if (user != null)
                {
                    await _logRepository.AddUserLogAsync(user, ipAddress, Constants.ActionsLoginFailure, "帐号或密码错误");
                }
                return this.Error(errorMessage);
            }

            user = await _userRepository.GetByUserNameAsync(userName);

            await _userRepository.UpdateLastActivityDateAndCountOfLoginAsync(user); // 记录最后登录时间、失败次数清零

            await _statRepository.AddCountAsync(StatType.UserLogin, user);

            var loginLog = Constants.ActionsLoginSuccess;
            //if (request.AppLogin) { loginLog = loginLog + "-移动端"; }
            await _logRepository.AddUserLogAsync(user, ipAddress, loginLog);

            var token = _authManager.AuthenticateUser(user, true);


            return new SubmitResult
            {
                User = user,
                Token = token
            };
        }
    }
}
